package com.thzy.bbs.thread;

import android.app.ProgressDialog;
import android.os.Handler;

import com.thzy.bbs.common.CommonUtils;
import com.thzy.bbs.common.Constants;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

/**
 * 下载apk线程
 *
 * @author
 * @date 2017/3/2 19:38
 */

public class DownApkThread extends Thread {
    private ProgressDialog progressDialog;
    private Handler handler;
    /**
     * 下载地址
     */
    private String url;
    /**
     * app名称
     */
    private String name;

    /**
     * apk下载目录
     */
    private String path;

    public DownApkThread(ProgressDialog progressDialog, Handler handler, String url, String name, String path) {
        this.progressDialog = progressDialog;
        this.handler = handler;
        this.url = url;
        this.name = name;
        this.path = path;
    }

    @Override
    public void run() {
        super.run();
        RequestParams requestParams = new RequestParams(url);
        requestParams.setAutoResume(true);
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        requestParams.setSaveFilePath(CommonUtils.getSDPath() + "/" + name);
        requestParams.setMaxRetryCount(1);
        //设置进度条风格，风格为圆形，旋转的
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                progressDialog.setCancelable(false);
                progressDialog.setMax((int) total / 1024);
                progressDialog.setProgress((int) current / 1024);
            }

            @Override
            public void onSuccess(File result) {
                progressDialog.dismiss();
                handler.sendEmptyMessage(Constants.HandlerCode.UPDATE);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                handler.sendEmptyMessage(Constants.HandlerCode.ERROR_DOWN);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
}
